import { sys } from 'cc'
import { Md5 } from './Md5'

const serviceHost = 'https://api.quyaohd.com/mini-game-api/'
const signKey = 'Bf3cJ8hZ7x2Lp1aG4sD9yK6tQ0mNrWuV'

const MiniGameService = {

	postData(url = '', params = {}) {
		return new Promise((resolve, reject) => {
			const xhr = new XMLHttpRequest()
			xhr.open('POST', url, true)
			if (sys.isNative) {
				xhr.setRequestHeader('Accept-Encoding', 'gzip,deflate')
			}
			xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
			// note: In Internet Explorer, the timeout property may be set only after calling the open()
			// method and before calling the send() method.
			xhr.timeout = 30000 // 30 seconds for timeout

			var paramStr = ''
			for (var item in params) {
				paramStr += item + '=' + encodeURIComponent(params[item]) + '&'
			}
			xhr.send(paramStr)
			xhr.onreadystatechange = () => {
				if (xhr.readyState === 4 && xhr.status >= 200 && xhr.status <= 500) {
					var response = xhr.responseText
					resolve(JSON.parse(response))
				}
			}
		})
	},

	parseQueryString(obj) {
		let str = ''
		for (let key in obj) {
			str += key + '=' + obj[key] + '&'
		}
		return str
	},

	generatePar(par) {
		const sdic = Object.keys(par).sort();
		const content_list = [];
		for (var ki in sdic) {
			content_list.push(sdic[ki] + '=' + par[sdic[ki]]);
		}
		let content = content_list.join('&');
		content += signKey;
		console.log(content);
		const sign = Md5.hashStr(content);
		console.log(sign);
		par.sign = sign;
	},

	/**
	 * 获取排行
	 * @param appId 	小游戏appId
	 * @param key 		排行榜key
	 * @param limit 	获取的行数
	 * @returns promise
	 */
	getRanking(appId: string, key: string, limit: number = 100) {
		const par = {
			appId: appId,
			key: key,
			limit: limit
		}
		this.generatePar(par)
		return this.postData(serviceHost + 'ranking/get', par)
	},

	/**
	 * 更新排行榜
	 * @param appId 	小游戏appId
	 * @param key 		排行榜key
	 * @param openId 	用户openId
	 * @param score 	用户排行榜分数
	 * @param info 		用户数据
	 * @returns promise
	 */
	updateRanking(appId: string, key: string, openId: string, score: number, info: string) {
		const par = {
			appId: appId,
			key: key,
			openId: openId,
			score: score,
			info: info
		}
		this.generatePar(par)
		return this.postData(serviceHost + 'ranking/update', par)
	}

}

export { MiniGameService }